/**
* @Description: 设置用户角色js
* @Param:
* @return:
* @Author: Mr.Yan
* @Date: 2018/12/6
*/
$(function () {
    init();
    setCheckRole();
})

/** 
* @Description: 初始化
* @Param:  
* @return:  
* @Author: Mr.Yan 
* @Date: 2018/12/6 
*/
function init() {
    layui.use(['form'], function () {
        var form = layui.form;
        // 角色数据集
        $.ajax({
            url: prefixRole + "/findAll",
            type: "get",
            async: false,
            success: function (data) {
                var errcode = data.errcode;
                var errmsg = data.errmsg;
                if (errcode == "0") {
                    // 字符串数组转数字数组
                    var RoleIds = $("#roleIds").val().split(",").map(Number) ;
                    var roles = data.data.roles;
                    for (var i = 0; i < roles.length; i++) {
                        var roleId = roles[i].roleId;
                        var roleName = roles[i].roleName;
                        // 判断是否存在 回现
                        var isChecked = RoleIds.indexOf(roleId) > -1? "checked==checked":"";
                        var option = "<input class=\"role\" type=\"checkbox\" name=\"role\" value=\""+ roleId +"\" title=\""+ roleName +"\" "+ isChecked +">";
                        $("#roles").append(option);
                    }
                    form.render();
                } else {
                    AjaxException(errmsg);
                }
            },
            error: function () {
                AjaxErro();
            }
        })
    })
}

/**
* @Description: 获取选中的input值
* @Param:
* @return:
* @Author: Mr.Yan
* @Date: 2018/12/6
*/
function setCheckRole() {
    $("#roles").bind('click','.role',function () {
        var arrRoleId = new Array();
        var arrRoleName = new Array();
        $("input:checkbox[name='role']:checked").each(function(i){
            arrRoleId[i] = $(this).val();
            arrRoleName[i] = $(this).attr("title");
        });
        //  数组拼接字符串
        var roleIds = arrRoleId.join(",");
        var roleNames = arrRoleName.join(",");
       $("#roleIds").val(roleIds);
       $("#roleNames").val(roleNames);
    })

}
